import 'package:flutter/material.dart';
import 'package:flutter_provider_demo/commons/log.dart';
import 'package:flutter_provider_demo/commons/result.dart';
import 'package:flutter_provider_demo/data/models/settings_model.dart';
import 'package:flutter_provider_demo/data/services/shared_preference.dart';

class SettingsRepository extends ChangeNotifier {
  SettingsRepository({
    required SharedPreference sharedPreference,
  }) : _sharedPreference = sharedPreference;

  final SharedPreference _sharedPreference;

  final _log = Log();
  bool _isInitialized = false;
  bool get isInitialized => _isInitialized;

  late SettingsModel _settingsModel;
  SettingsModel get settingsModel => _settingsModel;

  Future<Result<void>> initialize() async {
    if (_isInitialized) {
      return Result.ok(null);
    }

    bool darkMode = false;
    String language = 'en';

    final darkModeResult = await _sharedPreference.getBool(SharedKey.darkMode);
    if (darkModeResult is Ok) {
      darkMode = (darkModeResult as Ok).value ?? false;
    } else {
      _log.error('get dark mode error: ${(darkModeResult as Error).errorMessage()}');
    }
    final languageResult = await _sharedPreference.getString(SharedKey.language);
    if (languageResult is Ok) {
      language = (languageResult as Ok).value ?? 'en';
    } else {
      _log.error('get language error: ${(languageResult as Error).errorMessage()}');
    }
    _settingsModel = SettingsModel(
      themeMode: darkMode ? ThemeMode.dark : ThemeMode.light,
      language: language,
    );

    _isInitialized = true;
    notifyListeners();

    return Result.ok(null);
  }

  Future<Result<void>> updateDarkMode(bool value) async {
    _settingsModel = _settingsModel.copyWith(
      themeMode: value ? ThemeMode.dark : ThemeMode.light,
    );
    notifyListeners();
    return await _sharedPreference.setBool(SharedKey.darkMode, value);
  }

  Future<Result<void>> setLanguage(String value) async {
    final String language;
    if (value == 'zh' || value == 'Chinese') {
      language = 'zh';
    } else {
      language = 'en';
    }
    if (language == _settingsModel.language) {
      return Result.ok(null);
    }
    _settingsModel = _settingsModel.copyWith(
      language: language,
    );
    notifyListeners();
    return await _sharedPreference.setString(SharedKey.language, language);
  }
}
